import os
import time
import json

import pyautogui
import pyperclip


_CURRENT_PATH = os.path.abspath(__file__)
_DIR_PATH = os.path.abspath(os.path.dirname(_CURRENT_PATH) + os.path.sep + ".")
_CONFIG_FILE = os.path.join(_DIR_PATH, 'config.json')
with open(_CONFIG_FILE, encoding='UTF-8') as f:
    _CONFIG = json.load(f)


class Files(object):
    def __init__(self):
       pass

    def file_upload(self, user_list):
        pyautogui.hotkey('ctrl', 'alt', 'w')

        files_path = self.find_files(os.path.join(_DIR_PATH, _CONFIG["path"]))

        for user in user_list:
            self.find_user(user)
            for file_path in files_path:
                self.wechat_send(file_path)
                pyautogui.press('enter')

    def find_user(self, user):
        if user != '':
            pyperclip.copy(user)
            self.find_image("images\\search_user.png")
            pyautogui.hotkey('ctrl', 'v')
            time.sleep(2)

            pyautogui.moveRel(xOffset=0, yOffset=_CONFIG["offset"])
            pyautogui.click()
            time.sleep(2)

    def find_image(self, image):
        image_l = pyautogui.locateOnScreen(image, grayscale=True)
        time.sleep(2)
        center = pyautogui.center(image_l)

        pyautogui.click(center)

    def wechat_send(self, file_path):
        pyperclip.copy(file_path)
        self.find_image("images\\send_file.png")
        time.sleep(2)

        pyautogui.hotkey('ctrl', 'v')
        pyautogui.press('enter')
        time.sleep(2)

    def find_files(self, dir):
        files = []

        file_lists = os.listdir(dir)
        for file in file_lists:
            file = os.path.join(dir, file_lists[-1])
            files.append(file)
        
        return files


sender = Files()